/*
 * @Author: jiameng15
 * @Date: 2020-03-04 22:47:07
 * @Last Modified by: jiameng15
 * @Last Modified time: 2020-04-14 20:21:56
 */
<template>
  <div>
    <div class="row-header">
      <el-form ref="searchForm" :model="searchForm" label-width="50px" :inline="true">
        <el-form-item label=" " prop="startDate">
          <el-date-picker
            v-model="startDate"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="发布开始日期"
            end-placeholder="发布结束日期"
            style="width:  400px"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            @change="changeDate"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label=" " prop="endDate">
          <el-date-picker
            v-model="endDate"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="到期起始日期"
            end-placeholder="到期结束日期"
            style="width: 400px"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            @change="changeDate1"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label=" " prop="title">
          <el-input
            size="small"
            v-model="searchForm.title"
            placeholder="请输入公告标题"
            style="width:  300px;"
          ></el-input>
        </el-form-item>
        <el-form-item label=" " prop="dictOutType">
          <el-select
            size="small"
            placeholder="请选择通知类型"
            style="width:  300px;"
            v-model="searchForm.dictNoticeType"
          >
            <el-option value="PC" label="PC端"></el-option>
            <el-option value="C" label="C端"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="row-form-btn">
        <el-button type="shenda" size="mini" icon="el-icon-search" @click="beforeinitData()" >查询</el-button>
        <el-button type="shenda" size="mini" icon="el-icon-refresh-right" @click="resetForm('searchForm')" >重置</el-button>
      </div>
    </div>
    <div class="sd-page-line"></div>
    <div class="row-main">
      <el-button type="shenda" size="mini" icon="el-icon-refresh" @click="initData">刷新数据</el-button>
      <el-button type="shenda" size="mini" icon="el-icon-plus" @click="addNewNotice">新建公告</el-button>
      <el-table :data="tableData" ref="formData" v-loading.fullscreen="mainTableLoading" :pager-config="tablePage" class="row-main-table"
                :header-cell-style="{ 'background':$store.state.app.tableBgColor,'color':'#606266' }"
                 element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.2)">
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column prop="insertTimeDate" label="发布时间"></el-table-column>
        <el-table-column prop="expirationDate" label="到期时间"></el-table-column>
        <el-table-column prop="dictNoticeTypeName" label="通知类型"></el-table-column>
        <el-table-column prop="clickNumber" label="点击次数 "></el-table-column>
        <el-table-column label="操作" width="200">
          <template v-slot="{ row, rowIndex }">
            <el-button type="shendaWarning" @click="editEvent(row)" :loading="buttonRetryLoading" size="mini">修改</el-button>
            <el-button type="shendaDanger" @click="deleteNoticeConfirm(row)" :loading="buttonRetryLoading" size="mini">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div :style="{'overflow-x': $store.state.app.screenWidth<992?'scroll':'none'}">
        <el-pagination
          background
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="page.size"
          :total="page.total"
          :current-page="page.current"
          layout="total, sizes, prev, pager, next, jumper"
          class="row-main-pager">
        </el-pagination>
      </div>
    </div>

    <el-dialog
      class="delete"
      top="33vh"
      :visible.sync="deleteNoticeVisible"
      :append-to-body="true"
      width="30%"
    >
      <span style="display: flex; justify-content: center;">确定删除该公告</span>
      <span class="dialog-footer" slot="footer">
        <el-button @click="deleteNoticeVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="deleteNoticeFunc(deleteId)" size="small">确 定</el-button>
      </span>
    </el-dialog>
    <el-drawer
      class="drawer_form"
      size="100%"
      :title="noticeTitle"
      :visible.sync="drawer"
      direction="ttb"
      :before-close="handleClose"
    >
      <div class="sd-drawer-content notice_drawer_form">
        <div class="sd-drawer-content-pannel">
          <el-form label-position="top" ref="saveInfo" :model="saveInfo" :rules="formRules">
            <el-row>
              <el-col :xl="{ span: 20, push: 1 }" :lg="{ span: 20, push: 1 }">
                <el-form-item label="标题:" label-width="90px" prop="title">
                  <el-input
                    size="small"
                    v-model="saveInfo.title"
                    style="width: 100%;"
                    placeholder="请输入公告标题sdfadfadfadfa"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xl="{ span: 20, push: 1 }" :lg="{ span: 20, push: 1 }">
                <el-form-item label="图片:" label-width="90px" prop="photograph">
                  <el-upload
                    class="upload-demo"
                    :action="upload_qiniu_url"
                    :data="qiniuData"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :on-error="handleError"
                    :before-upload="beforeUpload"
                    ref="file"
                    accept="image/*"
                    drag
                    multiple
                    @change="changeImg"
                  >
                    <img
                      class="avatar"
                      v-if="saveInfo.picUrl"
                      :src="saveInfo.picUrl"
                      style="width:100%;height:100%"
                    />
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">
                      将图片拖到此处，或
                      <em>点击上传</em>
                    </div>
                    <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过2m</div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xl="{ span: 20, push: 1 }" :lg="{ span: 20, push: 1 }">
                <el-form-item label="内容:" label-width="90px" prop="contentText">
                  <editor :value.sync="saveInfo.contentText"></editor>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xl="{ span: 20, push: 1 }" :lg="{ span: 20, push: 1 }">
                <el-form-item label="发布次数:" label-width="90px" prop="sendNumber">
                  <el-input
                    size="small"
                    v-model="saveInfo.sendNumber"
                    style="width: 100%;"
                    :disabled="noticeTitle === '修改公告'"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xl="{ span: 20, push: 1 }" :lg="{ span: 20, push: 1 }">
                <el-form-item label="截止日期:" label-width="90px" prop="expirationDate">
                  <el-date-picker
                    style="width: 100%;"
                    value-format="yyyy-MM-dd"
                    format="yyyy-MM-dd"
                    v-model="saveInfo.expirationDate"
                    @change="changeDate"
                    placeholder="请选择截止日期"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xl="{ span: 20, push: 1 }" :lg="{ span: 20, push: 1 }">
                <el-form-item label="通知类型:" label-width="90px" prop="dictNoticeType">
                  <el-select
                    size="small"
                    placeholder="请选择通知类型"
                    style="width: 100%;"
                    v-model="saveInfo.dictNoticeType"
                  >
                    <el-option value="PC" label="PC端"></el-option>
                    <el-option value="C" label="C端"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <div class="sd-drawer-footer">
        <div class="buttons">
          <el-button
            @click="submitHandle('saveInfo')"
            size="small"
            type="primary"
            v-preventReClick
            style="margin-left: 10px"
          >提交</el-button>
          <!-- <el-button @click="handleClose" size="small">关闭</el-button> -->
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  outboundList,
  listForAgentForInntSelect,
  listOrdinaryUsers,
  getOrdinaryAgent,
  outboundOrderSave,
  outBoundAppointagent,
  getLoginName,
  excelDownload,
  uploadUserPicture, // 上传图片
  getNoticeList, // 获取公告列表
  saveNotice, // 保存公告
  deleteNotice // 删除公告
} from "@/api/getData";
import { getStore, setStore } from "@/config/mUtils";
import { subStringForExceptLetter } from "@/utils/utils";
import Editor from "@/components/Editor";

var qiniu = require("qiniu-js");
var imgUrl = localStorage.getItem("image");
export default {
  name: "StockOut",
  data() {
    return {

      wck: 0,
      nocolor_font: {},
      red_font_real: {
        color: "#ff0000"
      },

      // 图片上传
      upload_qiniu_addr: imgUrl,
      upload_qiniu_url: "https://upload.qbox.me",
      qiniuData: {},
      // 新增、修改-数据对象
      saveInfo: {
        title: "",
        contentText: "",
        sendNumber: "",
        expirationDate: "",
        dictNoticeType: "",
        clickNumber: "0",
        picUrl: ""
      },
      // 抽屉
      noticeTitle: "",
      drawer: false,
      direction: "ttb",

      formData: {
        id: null,
        title: null,
        contentText: null,
        sendNumber: null,
        expirationDate: null,
        dictNoticeType: null
      },
      typeList: [{ label: "PC端", value: "PC" }, { label: "C端", value: "C" }],
      // ----↓修改公告
      submitLoading: false,
      showEdit: false,
      deleteNoticeVisible: false,
      buttonRetryLoading: false,
      startDate: [],
      endDate: [],
      // 查询条件
      searchForm: {
        title: "",               // 标题
        dictNoticeType: "",      // 通知类型 选择框  pc端为PC   C端为 C
        startExpirationDate: "", // 发布开始时间
        startSendDate: "",       // 到期开始时间
        endExpirationDate: "",   // 发布结束时间
        endSendDate: ""          // 到期结束时间
      },
      // loading...
      loading: false,
      searchLoading: false,
      mainTableLoading: false,
      // 分页
      page: {
        current: 1,
        size: 10,
        total: 0,
        ascs: [],
        descs: ['insertTime']
      },
      //
      tablePage: {
        pageSize: 15,
        pageSizes: [5, 15, 20, 50, 100, 200, 500, 1000]
      },
      tableData: [],
      value: false,
      tableLoading: false,
      id: "",

      okloading: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      pagekey: '',
      formRules: {
        title: [{ required: true, message: "请输入公告标题", trigger: "blur" }],
        contentText: [
          { required: true, message: "请输入公告内容", trigger: "blur" }
        ],
        sendNumber: [
          { required: true, message: "请输入发布次数", trigger: "blur" }
        ],
        expirationDate: [
          { required: true, message: "请选择截止日期", trigger: "change" }
        ],
        dictNoticeType: [
          { required: true, message: "请选择通知类型", trigger: "change" }
        ]
      }
    };
  },
  components: {
    Editor
  },
  watch: {
    // "saveInfo.contentText": {
    //   handler(newName, oldName) {
    //     // console.log(this.saveInfo.contentText);
    //     this.checkWord();
    //   },
    //   immediate: true
    //   // deep: true
    // },
    user: function(val, oldval) {
      this.form.belongId = val.value;
      this.form.username = val.label;
    }
  },
  created() {
    // 读取session里的查询参数
    let searchObj = sessionStorage.getItem(this.$route.path);
    // console.log(searchObj)
    if (searchObj != undefined && searchObj != null && searchObj != "") {
      this.searchForm = JSON.parse(searchObj);
      // console.log(this.searchForm);
      if (this.searchForm.startSendDate) {
        this.startDate.push(this.searchForm.startSendDate);
      }
      if (this.searchForm.endSendDate) {
        this.startDate.push(this.searchForm.endSendDate);
      }
      if (this.searchForm.startExpirationDate) {
        this.endDate.push(this.searchForm.startExpirationDate);
      }
      if (this.searchForm.endExpirationDate) {
        this.endDate.push(this.searchForm.endExpirationDate);
      }
      this.page = this.searchForm.page;
    }
    this.initData();
  },

  methods: {
    changeImg() {
      // console.log()
    },
    // 定义函数显示写了几个字
    // checkWord() {
    //   let myLen = this.saveInfo.contentText.length; //计算已输入的字符个数
    // },
    // 图片上传-选择图片
    checkFile(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isPNG) {
        this.$message.error("图片只能是 JPG/PNG 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 2MB!");
        return false;
      }
      return true;
    },
    // 图片上传-成功事件
    handleAvatarSuccess: function(res, file) {
      this.saveInfo.picUrl = this.upload_qiniu_addr + res.key;
      // console.log(this.saveInfo.picUrl)
    },
    // 图片上传-失败事件
    handleError: function(res) {
      this.$message({
        message: "上传失败",
        duration: 2000,
        type: "warning"
      });
    },
    // 图片上传-接口
    async beforeUpload(file) {
      // console.log("bfupload");
      // this.qiniuData.key = file.name;
      if (!this.checkFile(file)) {
        return false;
      }
      let tk = await uploadUserPicture({ uploadType: 1 });
      this.qiniuData = tk.data;
    },
    // 新增
    async addNewNotice() {
      this.noticeTitle = "新建公告";
      this.pagekey = await this.$getPageKey();
      this.saveInfo = {
        title: "",
        contentText: "",
        sendNumber: "",
        expirationDate: "",
        dictNoticeType: "",
        clickNumber: "0",
        picUrl: ""
      };
      this.drawer = true;
    },
    // 编辑
    async editEvent(row) {
      this.pagekey = await this.$getPageKey();
      this.noticeTitle = "修改公告";
      this.saveInfo = {
        id: row.id,
        title: row.title,
        contentText: row.contentText,
        sendNumber: row.sendNumber,
        expirationDate: row.expirationDate,
        dictNoticeType: row.dictNoticeType,
        picUrl: row.picUrl
      };
      this.drawer = true;
      // this.showEdit = true
    },
    // 保存-校验
    submitHandle(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.saveNewNoticeFunc();
        } else {
          return false;
        }
      });
    },

    // 保存-接口
    async saveNewNoticeFunc() {
      const returnData = await saveNotice(this.saveInfo,{pagekey:this.pagekey});
      if (returnData._result) {
        this.$message.success("提交成功");
        this.initData();
        this.drawer = false;
      }
      this.pagekey = await this.$getPageKey();
    },
    // 删除
    deleteNoticeConfirm(row) {
      this.deleteId = row.id;
      this.deleteNoticeVisible = true;
    },
    // 删除-接口
    async deleteNoticeFunc(deleteId) {
      const returnData = await deleteNotice({
        id: deleteId
      });
      if (returnData._result) {
        this.$message.success("提交成功");
        this.deleteNoticeVisible = false;
        this.initData();
      }
    },
    // 发布时间区间
    changeDate() {
      // console.log(this.startDate);
      if (this.startDate) {
        this.searchForm.startSendDate = this.startDate[0];
        this.searchForm.endSendDate = this.startDate[1];
      } else {
        this.searchForm.startSendDate = "";
        this.searchForm.endSendDate = "";
      }
    },
    // 到期时间区间
    changeDate1() {
      // console.log(this.endDate);
      if (this.endDate) {
        this.searchForm.startExpirationDate = this.endDate[0];
        this.searchForm.endExpirationDate = this.endDate[1];
      } else {
        this.searchForm.startExpirationDate = "";
        this.searchForm.endExpirationDate = "";
      }
    },

    handleCurrentChange(currentPage) {
      this.page.current = currentPage;
      this.initData()
    },
    handleSizeChange(pageSize){
      this.page.current = 1;
      this.page.size = pageSize;
      this.initData()
    },
    // 关闭抽屉
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
          this.$refs.saveInfo.clearValidate();
          this.$refs.saveInfo.resetFields();
          // this.saveInfo={
          //   title:'',
          //   contentText:'',
          //   sendNumber:'',
          //   expirationDate:'',
          //   dictNoticeType:'',
          //   clickNumber:'0'
          // }
        })
        .catch(_ => {});
    },
    beforeinitData(){
      this.page.current = 1
      this.initData()
    },
    // 初始化-列表
    async initData(theKey) {
      this.mainTableLoading = true;
      this.searchForm.page = this.page;
      this.searchForm.page.descs=["insertTime"]

      // 保存查询参数到session
      sessionStorage.setItem(this.$route.path, JSON.stringify(this.searchForm));
      const returnData = await getNoticeList(this.searchForm, {
        obj: this,
        key: "tableLoading;" + theKey
      });
      this.tableData = [];
      //console.log(returnData)
      if (returnData._result) {
        // 数据回显
        returnData.data.records.map(item => {
          let data = {};
          data.id = item.id;
          data.oemId = item.oemId;
          data.title = item.title;
          data.picUrl = item.picUrl;
          data.contentText = item.contentText;
          data.sendNumber = item.sendNumber;
          data.dictNoticeType = item.dictNoticeType;
          data.dictNoticeTypeName = item.dictNoticeTypeName;
          data.insertTimeDate = item.insertTimeDate;
          data.expirationDate = item.expirationDate;
          data.clickNumber = item.dictNoticeType==='PC'?'-':item.clickNumber;
          this.tableData.push(data);
        });
        this.tableLoading = false;
        this.page.total = returnData.data.total;
      }
      this.mainTableLoading = false;
    },
    // 重置-查询条件
    resetForm(formName) {
      // this.$refs[formName].resetFields();
      this.startDate = "";
      this.endDate = "";
      this.searchForm = {
        title: "",               // 标题
        dictNoticeType: "",      // 通知类型 选择框  pc端为PC   C端为 C
        startExpirationDate: "", // 发布开始时间
        startSendDate: "",       // 到期开始时间
        endExpirationDate: "",   // 发布结束时间
        endSendDate: ""          // 到期结束时间
      };
    }
  }
};
</script>
<style scoped lang="scss">
.drawer_form {
  padding: 50px;
  overflow-y: auto;
}
.notice_drawer_form {
  width: 100%;
}
.recentAdd li {
  list-style: none;
  float: left;
  margin-right: 5px;
  line-height: 15px;
}
</style>
<style>
.el-drawer.ttb {
  width: 800px;
  left: 50%;
  margin-left: -400px;
  /* right:50%; */
}
</style>
